package com.burgeon.backend.EnterpriseWeChat.service.Impl;

import com.burgeon.backend.EnterpriseWeChat.entity.EWAccessToken;
import com.burgeon.backend.EnterpriseWeChat.entity.EWechat;
import com.burgeon.backend.EnterpriseWeChat.entity.QyCode;
import com.burgeon.backend.EnterpriseWeChat.mappers.EWInfoMapper;
import com.burgeon.backend.EnterpriseWeChat.mappers.EWQyCodeMapper;
import com.burgeon.backend.EnterpriseWeChat.rest.EWEmployee.FindEmployeeAll;
import com.burgeon.backend.EnterpriseWeChat.rest.EWEmployee.FindNotCourseEmp;
import com.burgeon.backend.EnterpriseWeChat.rest.EWEmployee.findEmployeeByOpenId;
import com.burgeon.backend.EnterpriseWeChat.rest.EWEmployee.findEmployeeByStore;
import com.burgeon.backend.EnterpriseWeChat.service.EWInfoService;
import com.burgeon.backend.EnterpriseWeChat.service.ex.UpDataException;
import com.burgeon.backend.EnterpriseWeChat.utils.QYCode;
import com.burgeon.backend.SHOPBACKEND.entity.vip.Employee;
import com.burgeon.backend.college.control_panel.entity.Exam;
import com.burgeon.backend.college.client_side.entity.ExamRecord;
import com.burgeon.backend.college.client_side.mappers.AppCollegeMapper;
import com.burgeon.backend.college.control_panel.entity.Course;
import com.burgeon.backend.college.control_panel.entity.CourseRecord;
import com.burgeon.backend.college.control_panel.mappers.BackendCollegeMapper;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.entity.User;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.mappers.UserMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class EWInfoServiceImpl implements EWInfoService {
    private final static Log logger = LogFactory.getLog(EWInfoService.class);
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private BackendCollegeMapper backendCollegeMapper;
    @Autowired
    private AppCollegeMapper appCollegeMapper;


    @Autowired
    private EWInfoMapper ewInfoMapper;
    @Autowired
    private EWQyCodeMapper ewQyCodeMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void sendEmpNewOrderMini(String userid, String orderNo, String token) {
        String accessToken = getAppAccessToken(token);

        if (null == accessToken) {
            return;
        }
        Info info = GetInfoByToken(token);
        //根究
        findEmployeeByOpenId findEmployeeByOpenId = new findEmployeeByOpenId(info.getUrl(), info.getAccount(),info.getPassword());
        Employee employee = null;
        User user = userMapper.getUserById(userid);
        System.err.println(user);;
        try {
            employee = findEmployeeByOpenId.getData(user.getOpenid());
            System.err.println(employee);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("企业微信发送新订单通知:"+e.getMessage()+"顾客信息："+user.getName()+user.getPhone());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm");
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
        HashMap data = new HashMap();
        HashMap miniprogram_notice = new HashMap();
        data.put("miniprogram_notice",miniprogram_notice);

        assert employee != null;
        System.err.println(employee.getNO());
        data.put("touser", employee.getNO());
        data.put("msgtype", "miniprogram_notice");

        miniprogram_notice.put("appid","wxe9e2cf353fb1d4ed");//小程序id
        miniprogram_notice.put("title","新的订单");


        ArrayList content_item = new ArrayList();
        HashMap mesMap = new HashMap();
        String a = "顾客"+user.getName();
//        if(a.length()>9){
//            mesMap.put("key",("顾客"+vipName).substring(0,9));
//        }else {
            mesMap.put("key","顾客姓名");
//        }

//        if(orderNo.length()>29){
//            mesMap.put("value",message.substring(0,29));
//        }else {
            mesMap.put("value",user.getName());
//        }

        HashMap dateMap = new HashMap();
        dateMap.put("key","时间");
        dateMap.put("value",sdf.format(new Date()));
        HashMap phoneMap = new HashMap();
        phoneMap.put("key","卡号");
        phoneMap.put("value",user.getPhone());
        HashMap orderNoMap = new HashMap();
        orderNoMap.put("key","订单编号");
        orderNoMap.put("value",orderNo);

        content_item.add(phoneMap);
        content_item.add(mesMap);
        content_item.add(dateMap);
        content_item.add(orderNoMap);

        miniprogram_notice.put("content_item",content_item);

        data.put("enable_duplicate_check",1);

        RestTemplate restTemplate = new RestTemplate();
        System.err.println(data);
        String str = restTemplate.postForObject(url, data, String.class);
        System.err.println(str);
    }

    private Info GetInfoByToken(String token) {
        return accountMapper.GetTokenData(token);
    }

    /**
     * 企业微信小程序消息提醒
     * @param toUser 客服账号
     * @param vipName 会员姓名
     * @param vipPhone 会员卡号
     * @param message 消息内容
     * @param token token vip/pages/vipChat
     */
    @Override
    public void sendEmpmessageReminding(String toUser, String vipName, String vipPhone, String message, String token,String openid,String vipUrl) {
        System.err.println("token====================="+token);
        String accessToken = getAppAccessToken(token);

        if (null == accessToken) {
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm");
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
        HashMap data = new HashMap();
        HashMap miniprogram_notice = new HashMap();
        data.put("miniprogram_notice",miniprogram_notice);

        data.put("touser", toUser);
        System.err.println("发送企业微信通知toUser================"+toUser);
        data.put("msgtype", "miniprogram_notice");

        miniprogram_notice.put("appid","wxe9e2cf353fb1d4ed");//小程序id
        miniprogram_notice.put("title","顾客消息");
        String encodeName = "";
        try {
            encodeName = URLEncoder.encode(vipName,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
        String page = "vip/pages/vipChat/vipChat?openid="+openid+"&header="+vipUrl+"&name="+encodeName;

        System.err.println("page========================"+page);
        logger.info("page========================"+page);
        miniprogram_notice.put("page",page);


        ArrayList content_item = new ArrayList();
        HashMap mesMap = new HashMap();
        String a = "顾客"+vipName;
        if(a.length()>9){
            mesMap.put("key",("顾客"+vipName).substring(0,9));
        }else {
            mesMap.put("key",("顾客"+vipName));
        }

        if(message.length()>29){
            mesMap.put("value",message.substring(0,29));
        }else {
            mesMap.put("value",message);
        }

        HashMap dateMap = new HashMap();
        dateMap.put("key","时间");
        dateMap.put("value",sdf.format(new Date()));
        HashMap phoneMap = new HashMap();
        phoneMap.put("key","卡号");
        phoneMap.put("value",vipPhone);

        content_item.add(phoneMap);
        content_item.add(mesMap);
        content_item.add(dateMap);

        miniprogram_notice.put("content_item",content_item);

        data.put("enable_duplicate_check",1);

        RestTemplate restTemplate = new RestTemplate();
        System.err.println(data);
        String str = restTemplate.postForObject(url, data, String.class);
        System.err.println(str);
    }

    /**
     * 向导购企业微信发消息
     * @param toUser 导购企业微信ID 由企业编号生成
     * @param content 消息内容
     * @param token
     */
    @Override
    public void empMessageReminding(String toUser,String content,String token) {
        String accessToken = getAppAccessToken(token);
        if (null == accessToken) {
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm");
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
        HashMap data = new HashMap();
        data.put("touser", toUser);
        data.put("msgtype", "text");
        data.put("agentid", "1000013");
        HashMap text = new HashMap();
        text.put("content",content);


        data.put("text", text);
        RestTemplate restTemplate = new RestTemplate();
        System.err.println(data);
        String str = restTemplate.postForObject(url, data, String.class);
        System.err.println(str);
    }

    @Override
    public void findDepartmentUser(String token) {
        String accessToken = getAccessToken(token);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=" + accessToken + "&department_id=1";

        RestTemplate restTemplate = new RestTemplate();

        String str = restTemplate.getForObject(url, String.class);
        System.err.println(str);
    }

    @Override
    public void queryDepartment(String token) {
        String accessToken = getAccessToken(token);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + accessToken;

        RestTemplate restTemplate = new RestTemplate();

        String str = restTemplate.getForObject(url, String.class);
        System.err.println(str);
    }

    @Override
    public void inviteEMP(String token) {
        String accessToken = getAccessToken(token);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/batch/invite?access_token=" + accessToken;
        HashMap data = new HashMap();

        ArrayList user = new ArrayList();
        user.add("111");
        data.put("user", user);
        RestTemplate restTemplate = new RestTemplate();
        System.err.println(data);
        String str = restTemplate.postForObject(url, data, String.class);
        System.err.println(str);

    }

    /**
     * 创建员工
     */
    @Override
    public void createEWEmp(String userid, String name, String mobile, String token) {
        String accessToken = getAccessToken(token);
//        String accessToken ="Q9oepVK6ITcyJSWITtqJMmz4khegg5pabvO7vP2UFntnJXn-OSKPUa1hH9QRyIFtg5bsS1LWtPt9IpcocS-vyJ1_x_J3Vfqr8E28STKHCByp4KUoPgzat20-LI1jKGIrk7BJ3eGHU0UyCWnevXt8bBSfgVLNPX0M1CSmcolDQ8zr1GmI4NNdSi5ePmlAQDmSenUNKosk3ok0Qyl6eYGSVg";
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=" + accessToken;

        HashMap data = new HashMap();
        data.put("userid", userid);
        data.put("name", name);
        data.put("mobile", mobile);
        ArrayList a = new ArrayList();
        a.add("1");
        data.put("department", a);
        RestTemplate restTemplate = new RestTemplate();
        String str = restTemplate.postForObject(url, data, String.class);
        System.err.println(str);


    }

    /**
     * 接收suiteTicket
     *
     * @param code 回调数据
     */
    @Override
    public void suiteTicket(String code) {
        System.err.println(code);
    }

    //获取accesstoken
    @Override
    public String getAccessToken(String token) {
        //参数 corpid  corpsecret

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
        String now = sdf.format(new Date());

        EWAccessToken accessToken = ewInfoMapper.getAccessToken(token);

        if (null == accessToken) {
            String newAccessToken = createAccessToken(token);
            ewInfoMapper.createAccessToken(newAccessToken, now, token);
            return newAccessToken;
        }

        if (!now.equals(accessToken.getDate()) || null == accessToken.getAccessToken() || "".equals(accessToken.getAccessToken())) {
            String newAccessToken = createAccessToken(token);
            ewInfoMapper.upAccessToken(newAccessToken, now, token);
            return newAccessToken;
        }

        return accessToken.getAccessToken();


    }

    @Override
    public String getAppAccessToken(String token) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
        String now = sdf.format(new Date());

        EWAccessToken accessToken = ewInfoMapper.getAppAccessToken(token);

        if (null == accessToken) {
            String newAccessToken = createAppAccessToken(token);
            ewInfoMapper.createAppAccessToken(newAccessToken, now, token);
            return newAccessToken;
        }

        if (!now.equals(accessToken.getDate()) || null == accessToken.getAccessToken()||"".equals(accessToken.getAccessToken())) {
            String newAccessToken = createAppAccessToken(token);
            ewInfoMapper.upAppAccessToken(newAccessToken, now, token);
            return newAccessToken;
        }

        return accessToken.getAccessToken();

    }

    @Override
    public String contactMeAccessToken(String token) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
        String now = sdf.format(new Date());

        EWAccessToken accessToken = ewInfoMapper.getContactAccessToken(token);

        if (null == accessToken) {
            String newAccessToken = createContactAccessToken(token);
            ewInfoMapper.createContactAccessToken(newAccessToken, now, token);
            return newAccessToken;
        }

        if (!now.equals(accessToken.getDate()) || null == accessToken.getAccessToken()||"".equals(accessToken.getAccessToken())) {
            String newAccessToken = createContactAccessToken(token);
            ewInfoMapper.upContactAccessToken(newAccessToken, now, token);
            return newAccessToken;
        }

        return accessToken.getAccessToken();
    }

    @Override
    public String qyContactMeCode(String token, String empNo) {
        System.err.println(empNo);;
        QYCode qyCode = new QYCode();
        List list = new ArrayList();
        list.add(empNo);
        String c =null;
        QyCode qyCode1 =  ewQyCodeMapper.getQyCodeByEmpNo(empNo,token);
        if (qyCode1 == null){

            String accessToken =contactMeAccessToken(token);
            com.alibaba.fastjson.JSONObject res = null;

            try {
                res = qyCode.updateNews(list,token,accessToken);
                if("0".equals(res.getString("errcode"))){
                    c =res.getString("qr_code");
                    ewQyCodeMapper.createQyCode(empNo,c,res.getString("config_id"),token);

                }else if("40098".equals(res.getString("errcode"))){
                    logger.info(res);
                    throw new UpDataException("请实名认证");
                }else {
                    logger.info(res);
                    throw new UpDataException(res.getString("errcode")+res.getString("errmsg"));
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }else {
            c = qyCode1.getQy_code();
        }

        System.err.println(c);
        return c;
    }

    @Override
    public void sendEmpNewOrderMiniZT(String userid, String orderId, String token, String store, String sinceDate) throws Exception {
        String accessToken = getAppAccessToken(token);

        if (null == accessToken) {
            return;
        }
        Info info = GetInfoByToken(token);
        findEmployeeByStore findEmployeeByStore = new findEmployeeByStore(info.getUrl(), info.getAccount(), info.getPassword());
        ArrayList<Employee> employees = findEmployeeByStore.getData(store);

        User user = userMapper.getUserById(userid);

        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm");
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
        HashMap data = new HashMap();
        HashMap miniprogram_notice = new HashMap();
        data.put("miniprogram_notice",miniprogram_notice);

        ArrayList<Object> list = new ArrayList<>();

        for (Employee employee:employees) {
            System.err.println("==="+employee.getName());
            data.put("touser", employee.getNO());
            data.put("msgtype", "miniprogram_notice");

            miniprogram_notice.put("appid","wxe9e2cf353fb1d4ed");//小程序id
            miniprogram_notice.put("title","新的自提订单");


            ArrayList content_item = new ArrayList();
            HashMap mesMap = new HashMap();

            mesMap.put("key","顾客姓名");
            mesMap.put("value",user.getName());

            HashMap dateMap = new HashMap();
            dateMap.put("key","时间");
            dateMap.put("value",sdf.format(new Date()));
            HashMap phoneMap = new HashMap();
            phoneMap.put("key","卡号");
            phoneMap.put("value",user.getPhone());
            HashMap orderNoMap = new HashMap();
            orderNoMap.put("key","订单编号");
            orderNoMap.put("value",orderId);
            HashMap sinceDateMap = new HashMap();
            sinceDateMap.put("key","自提日期");
            sinceDateMap.put("value",sinceDate);

            content_item.add(phoneMap);
            content_item.add(mesMap);
            content_item.add(dateMap);
            content_item.add(orderNoMap);
            content_item.add(sinceDateMap);

            miniprogram_notice.put("content_item",content_item);

            data.put("enable_duplicate_check",1);

            RestTemplate restTemplate = new RestTemplate();
            System.err.println(data);
            String str = restTemplate.postForObject(url, data, String.class);
            System.err.println(str);

        }
    }

    @Override
    public void sendNewCourseOrExamNotice(String token,String newCourseOrExamId,String flag) throws Exception {
        String accessToken = getAppAccessToken(token);

        if (null == accessToken) {
            return;
        }
        Info info = GetInfoByToken(token);
        FindEmployeeAll findEmployeeAll = new FindEmployeeAll(info.getUrl(), info.getAccount(), info.getPassword());
        ArrayList<Employee> employees = findEmployeeAll.getData();

        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
        HashMap data = new HashMap();
        HashMap miniprogram_notice = new HashMap();
        data.put("miniprogram_notice",miniprogram_notice);

        HashMap mesMap = new HashMap();
        HashMap endTimeMap = new HashMap();
        HashMap introduceOrExamdurationMap = new HashMap();

        if (flag == "KC"){

            Course course = backendCollegeMapper.findNewCourse(token,newCourseOrExamId);//课程内容
            miniprogram_notice.put("title","新的课程已发布，请及时学习");

            mesMap.put("key","课程名称");
            mesMap.put("value",course.getTitle());

            endTimeMap.put("key","课程结束时间");
            endTimeMap.put("value",course.getEndTime());

            introduceOrExamdurationMap.put("key","课程介绍");
            introduceOrExamdurationMap.put("value",course.getIntroduce());

        }else if(flag == "KS"){

            Exam exam = backendCollegeMapper.findNewExam(token,newCourseOrExamId);
            miniprogram_notice.put("title","新的考试已发布，请及时学习课程并参加考试");

            mesMap.put("key","考试课程");
            mesMap.put("value",exam.getCourseName());

            endTimeMap.put("key","考试结束时间");
            endTimeMap.put("value",exam.getEndTime());

            introduceOrExamdurationMap.put("key","考试时长");
            introduceOrExamdurationMap.put("value",exam.getExamDuration()+"分钟");

        }

        ArrayList content_item = new ArrayList();

        content_item.add(endTimeMap);
        content_item.add(mesMap);
        content_item.add(introduceOrExamdurationMap);

        miniprogram_notice.put("appid","wxe9e2cf353fb1d4ed");//小程序id

        miniprogram_notice.put("content_item",content_item);

        for (Employee employee:employees) {

            System.err.println("==="+employee.getName());
            data.put("touser", employee.getNO());
            data.put("msgtype", "miniprogram_notice");

            data.put("enable_duplicate_check",1);

            RestTemplate restTemplate = new RestTemplate();
            System.err.println(data);
            String str = restTemplate.postForObject(url, data, String.class);
            System.err.println(str);

        }

    }

    @Override
    public void sendNotCourseNotice(String token) throws Exception {

        //获取课程信息
        List<Course> courseList = backendCollegeMapper.findAllCourse(token);

        Info info = GetInfoByToken(token);
        FindEmployeeAll findEmployeeAll = new FindEmployeeAll(info.getUrl(), info.getAccount(), info.getPassword());
        ArrayList<Employee> employees = findEmployeeAll.getData();

        ArrayList<String> empAllIds = new ArrayList<>();//所有导购的ID

        for (Employee employee:employees) {
            empAllIds.add(employee.getId());
        }
        ArrayList<String> empIds = new ArrayList<>();//课程学习完成的导购ID

        String accessToken = getAppAccessToken(token);
        if (null == accessToken) {
            return;
        }
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;

        HashMap data = new HashMap();
        HashMap miniprogram_notice = new HashMap();
        data.put("miniprogram_notice",miniprogram_notice);

        for (Course course:courseList) {

            List<CourseRecord> courseRecordList = backendCollegeMapper.findCourseList(token,course.getId());
            for (CourseRecord courseRecord:courseRecordList) {
                empIds.add(courseRecord.getEmpid());
            }

            empAllIds.removeAll(empIds);//差集：即未学习的导购ID

            FindNotCourseEmp findNotCourseEmp = new FindNotCourseEmp(info.getUrl(), info.getAccount(), info.getPassword());
            ArrayList<Employee> notCourseEmpData = findNotCourseEmp.getData(empAllIds);//未学习课程的导购信息

            for (Employee notCourseEmp:notCourseEmpData) {

                System.err.println("==="+notCourseEmp.getName());
                data.put("touser", notCourseEmp.getNO());
                data.put("msgtype", "miniprogram_notice");

                miniprogram_notice.put("appid","wxe9e2cf353fb1d4ed");//小程序id
                miniprogram_notice.put("title","课程未学习，请及时学习");

                ArrayList content_item = new ArrayList();
                HashMap mesMap = new HashMap();

                mesMap.put("key","课程名称");
                mesMap.put("value",course.getTitle());

                HashMap endTimeMap = new HashMap();

                endTimeMap.put("key","课程结束时间");
                endTimeMap.put("value",course.getEndTime());

                HashMap introduceMap = new HashMap();

                introduceMap.put("key","课程介绍");
                introduceMap.put("value",course.getIntroduce());

                content_item.add(endTimeMap);
                content_item.add(mesMap);
                content_item.add(introduceMap);

                miniprogram_notice.put("content_item",content_item);

                data.put("enable_duplicate_check",1);

                RestTemplate restTemplate = new RestTemplate();
                System.err.println(data);
                String str = restTemplate.postForObject(url, data, String.class);
                System.err.println(str);
            }

        }

    }

    @Override
    public void sendNotExamNotice(String token) throws Exception {
        List<Exam> examList = backendCollegeMapper.findAllExam(token);

        Info info = GetInfoByToken(token);
        FindEmployeeAll findEmployeeAll = new FindEmployeeAll(info.getUrl(), info.getAccount(), info.getPassword());
        ArrayList<Employee> employees = findEmployeeAll.getData();

        ArrayList<String> empAllIds = new ArrayList<>();//所有导购的ID

        for (Employee employee:employees) {
            empAllIds.add(employee.getId());
        }
        ArrayList<String> empIds = new ArrayList<>();//已参加考试的导购ID

        String accessToken = getAppAccessToken(token);
        if (null == accessToken) {
            return;
        }
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;

        HashMap data = new HashMap();
        HashMap miniprogram_notice = new HashMap();
        data.put("miniprogram_notice",miniprogram_notice);

        for (Exam exam:examList) {
            List<ExamRecord> examRecordList = backendCollegeMapper.findExamRecordData(token,exam.getId());
            for (ExamRecord examRecord:examRecordList) {
                empIds.add(examRecord.getEmp_id());
            }
            empAllIds.removeAll(empIds);//求差集，取未参加导购的ID

            FindNotCourseEmp findNotCourseEmp = new FindNotCourseEmp(info.getUrl(), info.getAccount(), info.getPassword());
            ArrayList<Employee> notCourseEmpData = findNotCourseEmp.getData(empAllIds);//未参加考试的导购信息

            for (Employee notCourseEmp:notCourseEmpData) {

                System.err.println("==="+notCourseEmp.getName());
                data.put("touser", notCourseEmp.getNO());
                data.put("msgtype", "miniprogram_notice");

                miniprogram_notice.put("appid","wxe9e2cf353fb1d4ed");//小程序id
                miniprogram_notice.put("title","有课程考试未参加，请及时学习课程并参加考试");

                ArrayList content_item = new ArrayList();
                HashMap mesMap = new HashMap();

                mesMap.put("key","课程名称");
                mesMap.put("value",exam.getCourseName());

                HashMap endTimeMap = new HashMap();

                endTimeMap.put("key","考试结束时间");
                endTimeMap.put("value",exam.getEndTime());

                HashMap introduceMap = new HashMap();

                introduceMap.put("key","考试时长");
                introduceMap.put("value",exam.getExamDuration()+"分钟");

                content_item.add(endTimeMap);
                content_item.add(mesMap);
                content_item.add(introduceMap);

                miniprogram_notice.put("content_item",content_item);

                data.put("enable_duplicate_check",1);

                RestTemplate restTemplate = new RestTemplate();
                System.err.println(data);
                String str = restTemplate.postForObject(url, data, String.class);
                System.err.println(str);
            }

        }

    }


    private String createContactAccessToken(String token) {

        EWechat eWechat = ewInfoMapper.findEWechat(token);
        String ID = eWechat.getCorpid();
        String SECRET = eWechat.getContactMeSecret();
        System.err.println("seee"+SECRET);

        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + ID + "&corpsecret="+SECRET.replaceAll("(\r\n|\r|\n|\n\r)", "");;//

        RestTemplate restTemplate = new RestTemplate();
        String accessToken = "";
        try {
            System.err.println("123");
            System.err.println(url);
            System.err.println("123");
            String str = restTemplate.getForObject(url, String.class);
            System.err.println(str);
            accessToken = new JSONObject(str).getString("access_token");
        } catch (JSONException e) {
            System.err.println("获取access_token失败");

        }

        return accessToken;
    }

    private String createAppAccessToken(String token) {
        System.err.println("请求accesstoken================================="+token);
        EWechat eWechat = ewInfoMapper.findEWechat(token);
        String ID = eWechat.getCorpid();
        String SECRET = eWechat.getAppSecret();

        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + ID + "&corpsecret="+SECRET.replaceAll("(\r\n|\r|\n|\n\r)", "");//

        RestTemplate restTemplate = new RestTemplate();
        String accessToken = "";
        try {
            System.err.println("123");
            System.err.println(url);
            System.err.println("123");
            String str = restTemplate.getForObject(url, String.class);
            System.err.println(str);
            accessToken = new JSONObject(str).getString("access_token");
        } catch (JSONException e) {
            System.err.println("获取access_token失败");

        }

        return accessToken;
    }

    private String createAccessToken(String token) {

        EWechat eWechat = ewInfoMapper.findEWechat(token);
        String ID = eWechat.getCorpid();
        String SECRET = eWechat.getSecret();

        String url =
                "https://qyapi.weixin.qq.com/cgi-bin/gettoken?" +
                        "corpid=" + ID +"&corpsecret=" + SECRET.replace("\t\r\n","");

        String accessToken = "";

        RestTemplate restTemplate = new RestTemplate();

        try {
            String str = restTemplate.getForObject(url, String.class);
            accessToken = new JSONObject(str).getString("access_token");
        } catch (Exception e) {
            System.err.println("获取access_token失败");
            e.printStackTrace();
        }

        return accessToken;
    }

    /**
     * 2.发送Get请求
     *
     * @param url
     * @param params 表示链接后面的一些参数 如name=ghoset&pass=ghoset
     * @return
     */
    public String sendGet(String url, String params) throws Exception {
        StringBuilder builder = new StringBuilder();

        if (params != null || params.length() != 0) {
            url = url + "?" + params;   //重新构造URL链接
        }
        URL Url = new URL(url);
        URLConnection conn = Url.openConnection();
        // 设置代理
        //URLConnection conn = Url.openConnection(setProxy(proxyHost, proxyPort));
        // 如果需要设置代理账号密码则添加下面一行
        //conn.setRequestProperty("Proxy-Authorization", "Basic "+Base64.encode("account:password".getBytes()));

        //发送数据包(可以直接抓取浏览器数据包然后复制)
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36");

        conn.connect();

        //接收响应的数据包
        Map<String, List<String>> map = conn.getHeaderFields();
        Set<String> set = map.keySet();
        for (String k : set) {
            String v = conn.getHeaderField(k);
            System.out.println(k + ":" + v);
        }


        //返回浏览器的输出信息
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = reader.readLine();
        line = new String(line.getBytes(), "gbk");
        //实现将字符串转成gbk类型显示.
        while (line != null) {
            builder.append(line + "\r\n");
            System.out.println(line);
            line = reader.readLine();
        }

        //释放资源
        reader.close();

        return builder.toString();
    }


}
